//
//  BVClearCacheManager.m
//  XiangYu
//
//  Created by YYKJ on 2017/6/12.
//  Copyright © 2017年 YYKJ. All rights reserved.
//

#import "BVClearCacheManager.h"

@implementation BVClearCacheManager

-(void)notCache:(void(^)(NSString *str))notCache complete:(void(^)(NSString *str))complete{
    
     CGFloat cachesSize = [self getCachesSize];
     if(cachesSize <=0.001){
         notCache(@"没有缓存");
     }else{
         NSFileManager * fm = [NSFileManager defaultManager];
         NSString * path = [NSHomeDirectory() stringByAppendingPathComponent:@"Library/Caches"];
         BVLog(@"cachesSize  ===== %f", cachesSize);
         
         NSArray * array = [fm contentsOfDirectoryAtPath:path error:nil];
         for(NSString * str in array)
         {
             NSString * newPath = [path stringByAppendingPathComponent:str];
             [fm removeItemAtPath:newPath error:nil];
         }
         complete(@"清理完成");
     }

}

-(CGFloat)getCachesSize{
    NSString * path = [NSHomeDirectory() stringByAppendingPathComponent:@"Library/Caches"];
    return [self folderSizeAtPath:path];
}

/***  遍历文件夹获得文件夹大小，返回多少M*/
- (CGFloat ) folderSizeAtPath:(NSString*) folderPath{
    
    NSFileManager* manager = [NSFileManager defaultManager];
    
    if (![manager fileExistsAtPath:folderPath]) return 0;
    
    NSEnumerator *childFilesEnumerator = [[manager subpathsAtPath:folderPath] objectEnumerator];
    
    NSString* fileName;
    
    long long folderSize = 0;
    
    while ((fileName = [childFilesEnumerator nextObject]) != nil){
        
        NSString* fileAbsolutePath = [folderPath stringByAppendingPathComponent:fileName];
        
        folderSize += [self fileSizeAtPath:fileAbsolutePath];
    }
    
    // 图片缓存
    folderSize += [[SDImageCache sharedImageCache] getSize];
    
    return folderSize/(1024.0*1024.0);
}

/***  单个文件大小*/
- (long long) fileSizeAtPath:(NSString*) filePath{
    
    NSFileManager* manager = [NSFileManager defaultManager];
    
    if ([manager fileExistsAtPath:filePath]){
        return [[manager attributesOfItemAtPath:filePath error:nil] fileSize];
    }
    return 0;
}

@end
